<template>
  <div class="min-h-screen flex items-center justify-center bg-cover bg-center" 
       :style="{ backgroundImage: `url(${backgroundImage})` }">
    <div class="w-full max-w-md">
      <div class="text-center mb-6">
        <h1 class="text-2xl font-bold text-white">用户登录</h1>
      </div>
      
      <div class="bg-white p-6 rounded-lg shadow-md">
        <form @submit.prevent="loginBtn" class="space-y-4">
          <div>
            <label for="username" class="block text-sm font-medium text-gray-700">帐号</label>
            <input
              type="text"
              id="username"
              v-model="acount"
              placeholder="请输入账号"
              class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
            />
          </div>
          
          <div>
            <div class="flex justify-between">
              <label for="password" class="block text-sm font-medium text-gray-700">密码</label>
              <a href="#" class="text-sm text-indigo-600 hover:text-indigo-500">忘记密码？</a>
            </div>
            <input
              type="password"
              id="password"
              v-model="password"
              placeholder="Password"
              class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
            />
          </div>
          
          <div class="flex items-center">
            <input
              id="remember-me"
              name="remember-me"
              type="checkbox"
              class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"
            />
            <label for="remember-me" class="ml-2 block text-sm text-gray-900">记住密码</label>
          </div>
          
          <button
            type="submit"
            class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-[#007029] hover:bg-[#005d22] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
          >
            登录
          </button>
        </form>
        
        <!-- <div class="mt-4 text-center text-sm text-white">
          <p>没有账号? <router-link to="/register" class="text-indigo-600 hover:text-indigo-500">立即注册</router-link></p>
        </div> -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import riceImg from "@/assets/img/rice.png";
import { apiClient } from "../api/apiService.js";
import { ElMessage } from 'element-plus';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { Base64 } from 'js-base64'; // 解构导入 Base64 类

const store = useStore();
const router = useRouter();

const acount = ref('');
const password = ref('');
const backgroundImage = riceImg;

const loginBtn = async () => {
  try {
    if (!acount.value) {
      alert("用户名不能为空")
      return
    }
    
    if (!password.value) {
      alert("密码不能为空")
      return
    }
    
    await userLogin();
  
  } catch (err) {
    console.error(err)
  }
}

// 用户登录
const userLogin = async () => {
  try {
    const param = ref({});
    param.value = {
    username: acount.value,
    password: password.value
    };
    const response = await apiClient.post(`user/login`, param.value, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: window.localStorage.token,
      },
    });
    if (response.flag == true) {
        // 在Vuex中存储token
        store.commit('setToken', response.data);

        const [, payload] = response.data.split('.');
        const decoded = Base64.decode(payload);
        const { nickname, avatar, role } = JSON.parse(decoded);
    
       store.commit('updateLoginUserNickname', nickname);
       store.commit('updateLoginUserAvatar', avatar);
       store.commit('updateRole', role);

        //跳转至首页
        router.push("/intelligentMatch").catch((err) => err);
    } else {
        ElMessage.error(response.message);
    }
  } catch (error) {
    console.error("请求失败", error);
    throw error;
  }
};
</script>

<style scoped>
/* 可以保留一些自定义样式，但大部分样式已由Tailwind处理 */
</style>